package com.kly.controller;

import com.kly.common.ErrorCode;
import com.kly.common.Result;
import com.kly.exception.BusinessException;
import com.kly.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 * 上传文件控制器
 *
 * @author admin
 * @date 2025/3/1
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {

    @Resource
    private AliOssUtil aliOssUtil;

    @PostMapping("/image")
    public Result<String> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件为空");
            }

            // 创建临时文件保存上传内容
            File tempFile = File.createTempFile("upload-", file.getOriginalFilename());
            file.transferTo(tempFile);

            // 获取文件后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

            // 上传到OSS（使用临时文件路径）
            String url = aliOssUtil.upload(tempFile.getAbsolutePath(), suffix);

            // 删除临时文件
            tempFile.delete();

            return Result.success(url);
        } catch (Exception e) {
            throw new RuntimeException("文件处理失败", e);
        }
    }

}